<template>
    <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" :rules="rules"
      label-width="auto" class="demo-ruleForm" :size="formSize" status-icon>

      <el-form-item label="商品名称" prop="Goods_Name">
        <el-input v-model="ruleForm.Goods_Name" />
      </el-form-item>

      <el-form-item label="商品品牌" prop="GB_Id">
        <el-select v-model="ruleForm.GB_Id" placeholder="请选择">
          <el-option label="--请选择--" value="0" />
          <el-option v-for="item in brandList" :label="item.GB_Name" :value="item.GB_Id" />
        </el-select>
      </el-form-item>

      <el-form-item label="商品分类" prop="newGT_ID">
        <el-cascader v-model="ruleForm.newGT_ID" :options="options" :props="props" @change="handleChange" />
        {{ ruleForm.GT_Id }}
      </el-form-item>

      <el-form-item label="价格" required prop="Goods_Price">
        <el-input v-model="ruleForm.Goods_Price" />
      </el-form-item>
      
      <el-form-item label="图片" prop="delivery">
        <el-upload class="avatar-uploader" action="https://localhost:44376/api/Files/FileUpLoads"
      :show-file-list="false"
      :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload">

      <img v-if="ruleForm.Goods_Img" :src="ruleForm.Goods_Img" class="avatar" />
      <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
    </el-upload>
      </el-form-item>

      <el-form-item label="状态" prop="Goods_State">
        <el-radio-group v-model="ruleForm.Goods_State">
          <el-radio :value="true">上架</el-radio>
          <el-radio :value="false">下架</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="商品详情" prop="Goods_Desx">
        <div style="border: 1px solid #ccc">
    <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef" :defaultConfig="toolbarConfig" :mode="mode"/>
    <Editor style="height: 500px; overflow-y: hidden;" v-model="ruleForm.Goods_Desx" :defaultConfig="editorConfig" :mode="mode"
      @onCreated="handleCreated"/>
  </div>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm(ruleFormRef)">
          提交
        </el-button>
        <el-button @click="resetForm(ruleFormRef)">清空</el-button>
      </el-form-item>
    </el-form>
  </template>
  
  <script lang="ts" setup>
  import { reactive, ref,onMounted,onBeforeUnmount, shallowRef } from 'vue'
  import type { ComponentSize, FormInstance, FormRules,UploadProps } from 'element-plus'
  import axios from 'axios'
  import { ElMessage } from 'element-plus'
  import { Plus } from '@element-plus/icons-vue'
  import '@wangeditor/editor/dist/css/style.css' // 引入 css
  import { Editor, Toolbar } from '../../../node_modules/@wangeditor/editor-for-vue'
  import {useRoute,useRouter} from 'vue-router'

    const route = useRoute();

    const router = useRouter();

  //创建响应式数据用于接受商品品牌信息
  const brandList = ref([{
    GB_Id:0,
    GB_Name:""
  }]);
  

  
  const formSize = ref<ComponentSize>('default')
  const ruleFormRef = ref<FormInstance>()
  const ruleForm = reactive({
    Goods_Id:'',
    Goods_SnowId:'',
    Goods_Name: '',
    GB_Id: '',
    GT_Id: '',
    Goods_Price: '',
    Goods_Img: '',
    Goods_Desx: '',
    Goods_State:true,
    newGT_ID:[]
  })
  
  
  const rules = reactive<FormRules>({
    Goods_Name: [
      { required: true, message: '请输入商品名称', trigger: 'blur' },
      { min: 3, max: 20, message: '商品名称需输入3-20个字符', trigger: 'blur' },
    ],
    GB_Id: [
      {
        required: true,
        message: '请选择品牌',
        trigger: 'change',
      },
    ],
    newGT_ID: [
      {
        required: true,
        message: '请选择商品分类',
        trigger: 'change',
      },
    ],
    Goods_Price: [
      {
        required: true,
        message: '请输入价格',
        trigger: 'change',
      },
    ],
    Goods_State: [
    {
      required: true,
      message: '请选择状态',
      trigger: 'change',
    },
  ],
  Goods_Desx: [
      { required: true, message: '请输入商品描述', trigger: 'blur' }
    ],
  })
  
  const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
      if (valid) {
        ruleForm.GT_Id=ruleForm.newGT_ID.toString()

       axios.put("https://localhost:44376/api/Goods/EditGoodsInfo",ruleForm)
       .then(res=>{
        console.log(res.data);
          if(res.data.IsSuccess==true)
          {
             ElMessage.success('商品信息修改成功');
             router.push('/ShowGoods');
          }
          else{
            ElMessage.error('商品信息修改失败');
          }
       })




      } else {
        console.log('error submit!', fields)
      }
    })
  }
  
  const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
  }
  

  //创建声明周期函数钩
  onMounted(()=>{
    LoadGoodsBrand();
    GetData();
  })


    
  const value = ref([])
  
  const props = {
    expandTrigger: 'hover' as const,
  }
  
  const handleChange = (value:any) => {
    console.log(value)
  }
  
  const options = ref([])

  //加载商品品牌、商品分类
  const LoadGoodsBrand=()=>{
    axios.get("https://localhost:44376/api/Goods/ShowGoodsBrand")
    .then(res=>{
      console.log(res.data);
      brandList.value=res.data.Data
    })
   
    axios.get("https://localhost:44376/api/Goods/GetCascaderItemInfo?Pid=0")
    .then(res=>{
        console.log(res.data);
        options.value=res.data.Data
    })
    .catch(error=>{
        console.log(error);
    })

  }


  

  //完成文件上传方法
  const handleAvatarSuccess=(perObj:any)=>{
    ruleForm.Goods_Img=perObj.Comm_Path;
  }
  
  //文件上传前的验证
  const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    if (rawFile.type !== 'image/jpeg') {
      ElMessage.error('上传文件的类型必须为.JPG')
      return false
    } else if (rawFile.size / 1024 / 1024 > 2) {
      ElMessage.error('文件大小不得超过2MB!')
      return false
    }
    return true
  }




const mode=ref();

   // 编辑器实例，必须用 shallowRef
   const editorRef = shallowRef()

// 内容 HTML
const valueHtml = ref('<p>hello</p>')


const toolbarConfig = {}
const editorConfig = { placeholder: '请输入内容...' }

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})

const handleCreated = (editor:any) => {
  editorRef.value = editor // 记录 editor 实例，重要！
}


//获取所有商品信息
const GetData=()=>{
    axios.get("https://localhost:44376/api/Goods/GetGoodsInfo?SnowGoodsId="+route.params.Gid)
    .then(res=>{
        let info=res.data.Data;
        ruleForm.Goods_Name=info.Goods_Name;
        ruleForm.Goods_Img=info.Goods_Img;
        ruleForm.GB_Id=info.GB_Id;
        ruleForm.newGT_ID=info.GT_Id.split(',').map((ele:string)=>Number(ele));    //拿到的数据2，5，10
        ruleForm.Goods_Price=info.Goods_Price;
        ruleForm.Goods_Desx=info.Goods_Desx;
        ruleForm.Goods_State=info.Goods_State;
        ruleForm.Goods_Id=info.Goods_Id;
        ruleForm.Goods_SnowId=info.Goods_SnowId;
    })
}

  </script>
  
  <style scoped>
  .avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  </style>
  
  <style>
  .avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
  }
  
  .avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
  }
  
  .el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
  }
  </style>
  